package portal.mybatis.dao.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import beans.AlgorithmDetail;
import portal.mybatis.dao.SockectLog;
import portal.mybatis.dao.mapper.AlgorithmMapper;
@Service
public class AlgorithmService {
	@Autowired
	AlgorithmMapper algMapper;
	@Autowired
	HistoryJobService hjService;
	@Autowired
	SockectLogService slService;
	@Autowired
	HistoryAlgorithmService haService;
	public String getAlgorithmNameById(String algorithmId){
		return algMapper.getAlgorithmNameById(algorithmId);
		//return null;
	}
	public JSONObject getVersionInfoById(String algorithmId){
		List<AlgorithmDetail>list =algMapper.getVersionInfoById(algorithmId);
		if(list ==null || list.size()==0)
		return null;
		return JSONObject.parseObject(JSON.toJSONString(list.get(0)));
	}
	public int updateVersionInfoById(String algorithmId, String ftpUri, String ftpVersion){
		return 0;
	}
	public AlgorithmDetail selectLocationUri(String algorithmId){
		AlgorithmDetail alg=new AlgorithmDetail();
		alg.setId(Integer.valueOf(algorithmId));
		return algMapper.selectLocationUri(alg);
	}
	public boolean updatealgorithmState(int state,List<String> runningJobIds, String subTaskHash, String algorithmHash) {
		String status="";
		boolean ret=true,endAlg=false;
		Date time=null;
		switch(state){
		case 1:status="DONE";endAlg=true;break;
		case 2:status="RUNNING";break;
		case 3:status="PAUSE";break;
		case 4:{status="EXIT";time=new Date();endAlg=true;state=5;}break;
		case 5:{status="STOP";time=new Date();}break;
		default:status="Unkonwn Code:"+state;break;
		}
		for(String jobId:runningJobIds){
			ret=ret && hjService.updateJobState(status, jobId, "", subTaskHash, algorithmHash, jobId);
//			ret=ret && slService.updateByKeySelective(new SockectLog(jobId,state+"",time));
		}
		if(endAlg){
			ret =ret && haService.updateEndTimeByKey(subTaskHash,algorithmHash);
		}
		return ret;
	}
}
